package com.mc.moring.main.personal

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar
import com.mc.moring.BafBase.BAFBaseActivity
import com.mc.moring.R
import com.mc.moring.app.LogUtils
import com.mc.moring.base.HttpCallback
import com.mc.moring.bean.AppConfigBean
import com.mc.moring.bean.AppVersionBean
import com.mc.moring.bean.VersionBean
import com.mc.moring.bean.getWebLinkConfigBean
import com.mc.moring.main.WebViewActivity
import com.mc.moring.main.modle.MianModle
import com.mc.moring.network.HttpResult
import com.mc.moring.util.GsonUtils
import com.mc.moring.util.SharePreUtil
import com.mc.moring.util.ToastUtils
import com.mc.moring.widge.UpdateVersionDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * about us
 * author: Created by nao on 2019/1/14
 * version: 1.0.0
 */
class AboutActivity : BAFBaseActivity<AboutActivity>() {
    private val btn_back by lazy { findViewById<ImageButton>(R.id.abBackIBtn) }
    private val tv_item1 by lazy { findViewById<TextView>(R.id.tv_item1) }
    private val tv_item2 by lazy { findViewById<TextView>(R.id.tv_item2) }
    private val tv_item3 by lazy { findViewById<TextView>(R.id.tv_item3) }
    private val tv_item4 by lazy { findViewById<TextView>(R.id.tv_item4) }
    private val tv_item6 by lazy { findViewById<TextView>(R.id.tv_item6) }
    private val phone_layout by lazy { findViewById<RelativeLayout>(R.id.phone_layout) }
    private val whatsapp_layout by lazy { findViewById<RelativeLayout>(R.id.whatsapp_layout) }
    private val tv_item_check_update by lazy { findViewById<TextView>(R.id.tv_item_check_update) }
    private val tv_item_left_check_update by lazy { findViewById<TextView>(R.id.tv_item_left_check_update) }
    private val red_coin by lazy { findViewById<ImageView>(R.id.red_coin) }
    private val tv_item_term by lazy { findViewById<TextView>(R.id.tv_item_term) }
    private val tv_item_policy by lazy { findViewById<TextView>(R.id.tv_item_policy) }

    private val abTitleTV by lazy { findViewById<TextView>(R.id.abTitleTV) }
    private val tv_version by lazy { findViewById<TextView>(R.id.tv_version) }

    private val tv_msg by lazy { findViewById<TextView>(R.id.tv_msg) }
    private val tv_hint by lazy { findViewById<TextView>(R.id.tv_hint) }

    var isLatestVersion: Boolean? = true

    var updateVersionDialog: UpdateVersionDialog? = null

    var urlBean: getWebLinkConfigBean? = null
    var mianModle: MianModle? = null

    var appConfigBean: AppConfigBean? = null
    var versionBean: VersionBean? = null


    override fun initLayout() = R.layout.activity_about

    override fun initParameter(bundle: Bundle?) {}

    override fun afterInjectView() {
        Log.e("----inActivity","1");
        abTitleTV.text = "Acerca de nosotros"
        tv_version.text = "v${getVersion()}"
        if (!TextUtils.isEmpty(SharePreUtil.getStringData("_getWebLinkConfig"))) {
            urlBean = Gson().fromJson(
                SharePreUtil.getStringData("_getWebLinkConfig"),
                getWebLinkConfigBean::class.java
            )
            tv_item1.text = urlBean?.data?.facebookUrl
            tv_item2.text = urlBean?.data?.webUrl
            tv_item_policy.text = urlBean?.data?.privacyPolicy
            tv_item_term.text = urlBean?.data?.termUse

            updateVersionDialog = UpdateVersionDialog(this)
            tv_item1.setOnClickListener {
                var intent = Intent(this@AboutActivity, WebViewActivity::class.java)
                intent.putExtra("url", tv_item1.text)
                startActivity(intent)
            }
            tv_item2.setOnClickListener {
                var intent = Intent(this@AboutActivity, WebViewActivity::class.java)
                intent.putExtra("url", tv_item2.text)
                startActivity(intent)
            }

            tv_item_policy.setOnClickListener {
                if (!tv_item_policy.text.isNullOrEmpty()) {
                    var intent = Intent(this@AboutActivity, WebViewActivity::class.java)
                    intent.putExtra("url", tv_item_policy.text)
                    startActivity(intent)
                }
            }

            tv_item_term.setOnClickListener {
                if (!tv_item_term.text.isNullOrEmpty()) {
                    var intent = Intent(this@AboutActivity, WebViewActivity::class.java)
                    intent.putExtra("url", tv_item_term.text)
                    startActivity(intent)
                }
            }
        }
        tv_item_check_update.setOnClickListener {
            if (isLatestVersion == true){
                ToastUtils.showLong(this@AboutActivity, "Actualmente es la última versión")
            } else {
                updateVersionDialog?.showToUpdateDialog(this@AboutActivity, versionBean, false)
            }
        }

        tv_item_left_check_update.setOnClickListener {
            if (isLatestVersion == true){
                ToastUtils.showLong(this@AboutActivity, "Actualmente es la última versión")
            } else {
                updateVersionDialog?.showToUpdateDialog(this@AboutActivity, versionBean, false)
            }
        }

        tv_item3.setOnClickListener {
            try {
                val webUrl = appConfigBean?.data?.contactEmail ?: ""
                val email = arrayOf(webUrl)
                val intent = Intent(Intent.ACTION_SENDTO)
                intent.data = Uri.parse("mailto:")
                intent.putExtra(Intent.EXTRA_EMAIL, email)
                startActivity(intent);
            } catch (e: Exception) {
                e.printStackTrace()
                ToastUtils.showLong(this@AboutActivity, "No hay aplicación de buzón")
            }
        }
        if ( appConfigBean?.data?.whatApp == null || appConfigBean?.data?.whatApp!!.isEmpty() ){
            whatsapp_layout.visibility = View.GONE
        }
        if ( appConfigBean?.data?.contactNumber == null || appConfigBean?.data?.contactNumber!!.isEmpty() ){
            phone_layout.visibility = View.GONE
        }
        tv_item4.setOnClickListener {
            val phoneNumber = appConfigBean?.data?.contactNumber
            val intent = Intent(Intent.ACTION_DIAL)
            intent.data = Uri.parse("tel:$phoneNumber")
            startActivity(intent)
        }

        tv_item6.setOnClickListener {

            val phoneNumber = appConfigBean?.data?.whatApp
            val intent = Intent(Intent.ACTION_DIAL)
            intent.data = Uri.parse("tel:$phoneNumber")
            startActivity(intent)
        }
        initEvent()
        ImmersionBar.with(this)
            .fitsSystemWindows(true)
            .statusBarColor(R.color.white)
            .statusBarDarkFont(true)
            .init()

        tv_hint.isSelected = false
        tv_hint.text = "Saber más"
        tv_hint.setOnClickListener {
            tv_hint.isSelected = !tv_hint.isSelected
            if (tv_hint.isSelected) {
                setLine(false)
                tv_hint.text = "Colapsar"
            } else {
                setLine(true)
                tv_hint.text = "Saber más"
            }
        }
    }

    public override fun onStop() {
        super.onStop()
        hideMyLoading()
    }

    override fun hideLoading() {
    }

    override fun showLoading(msg: String?) {
    }

    private fun setLine(isHint: Boolean) {
        tv_msg.maxLines = if (isHint) 3 else 10000
    }

    fun initEvent() {
        LogUtils.logE("about us page")
        checkUpdateVersion()//进入该页面之后进行一次页面检查
        btn_back.setOnClickListener {
            // 执行点击事件触发的代码块
            finish()
        }
        mianModle = MianModle.instant
        var params: HashMap<String, String> = HashMap()
        showMyLoading()
        mianModle?.securitygetApplicationConfig(params, object : HttpCallback {
            override fun onSuccess(data: String) {
                LogUtils.logE("---about--securitygetApplicationConfig--data:$data")
                appConfigBean = GsonUtils.getGson().fromJson(data, AppConfigBean::class.java)
                if (appConfigBean != null && appConfigBean?.code == "0000") {
                    runOnUiThread {
                        tv_item3.text = appConfigBean?.data?.contactEmail
                        tv_item4.text = appConfigBean?.data?.contactNumber
                        tv_item6.text = appConfigBean?.data?.whatApp
                    }
                }
                hideMyLoading()
            }

            override fun onFaill(e: String) {
                hideMyLoading()
            }

        })
        updateVersionDialog!!.setDialogViewOnClickListener(object :
            UpdateVersionDialog.DialogViewOnClickListener {
            override fun onClickConfirm() {
                val intent = Intent(Intent.ACTION_VIEW)
                intent.data =
                    Uri.parse("market://details?id=${this@AboutActivity.packageName}")
                startActivity(intent)
            }
            override fun onClickCancel(isForce: Boolean) {

            }
        })
    }

    private fun getVersion(): String {
        return try {
            val manager = this.packageManager
            val info = manager.getPackageInfo(this.packageName, 0)
            info.versionName
        } catch (e: Exception) {
            ""
        }
    }

    private fun checkUpdateVersion() {
        lifecycleScope.launch(Dispatchers.IO){
            val map: MutableMap<String, String> = HashMap()
            val targetVersion = getVersion()
            map["version"] = targetVersion?:""
            val result: HttpResult<String> = MianModle.instant.getVersion(map)
            Log.e("----result",result.toString())
            when(result) {
                is HttpResult.Success -> {
                    val data = result.value
                    val (code, _, versionData) = Gson().fromJson(data, AppVersionBean::class.java)
                    versionBean = versionData
                    Log.e("----versionBean", GsonUtils.getGson().toJson(versionBean))
                    if (!versionBean?.version.isNullOrEmpty()) {
                        runOnUiThread {
                            if (versionBean?.version != targetVersion) {
                                Log.e("----targetVersion",targetVersion)
                                versionBean?.version?.let { Log.e("----version", it) }
                                red_coin.visibility = View.VISIBLE
                                isLatestVersion = false
                            } else {
                                red_coin.visibility = View.GONE
                                isLatestVersion = true
                            }
                        }
                    } else {
                        red_coin.visibility = View.GONE
                        isLatestVersion = true
                    }

                }
                is HttpResult.Failure -> {
                }
            }
        }
    }
}
